﻿using System;
using System.Collections.Generic;
using BSDS.Core.Model.Services;
using BSDS.Core.Model.Services.Geocoding;
using BSDS.Core.Model.Services.Jobs;
using BSDS.Core.Model.Services.Jobs.Core;
using BSDS.Core.Model.Services.Uploading;

namespace BSDS.Commands.Commands.Implementation.Jobs
{
    public class CleanJobsCommand : CommandBase
    {
        private readonly JobRepository repository;
        private readonly GeocodingService geocodingService;
        private readonly UploadService uploadService;
        private readonly DownloadService downloadService;

        public CleanJobsCommand(JobRepository repository, GeocodingService geocodingService, UploadService uploadService,
            DownloadService downloadService)
        {
            this.repository = repository;
            this.geocodingService = geocodingService;
            this.uploadService = uploadService;
            this.downloadService = downloadService;
        }

        public override CommandResult Execute(ExecutionContext context)
        {
            CleanUp(repository.GetAllGeocodeJobs(), geocodingService);
            CleanUp(repository.GetAllUploadJobs(), uploadService);
            CleanUp(repository.GetAllDownloadJobs(), downloadService);

            return CommandResult.Success();
        }

        private void CleanUp(IEnumerable<Job> jobs, IJobStateProvider stateProvider)
        {
            foreach (var job in jobs)
            {
                var jobStatus = stateProvider.QueryState(job.Id).Status;

                if (jobStatus == JobStatus.Aborted || jobStatus == JobStatus.Completed)
                {
                    repository.CleanUp(job.Id);

                    Console.WriteLine(string.Format("Job {0} cleaned.", job.Id));
                }
            }
        }
    }
}